package com.atguigu.chapter09;

import com.atguigu.chapter05.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/3/10 9:51
 */
public class Flink01_CEP_Demo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .readTextFile("input/sensor-cep.csv")
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        // 切分
                        String[] line = value.split(",");
                        return new WaterSensor(line[0], Long.valueOf(line[1]), Integer.valueOf(line[2]));

                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((value, ts) -> value.getTs() * 1000L)
                );


        // TODO CEP - 基本使用
        // 1.定义规则
        Pattern<WaterSensor, WaterSensor> pattern = Pattern
                .<WaterSensor>begin("start")
                .where(
                        new SimpleCondition<WaterSensor>() {

                            @Override
                            public boolean filter(WaterSensor value) throws Exception {
                                return "sensor_1".equals(value.getId());
                            }
                        }
                );

        // 2.应用规则
        PatternStream<WaterSensor> sensorPS = CEP.pattern(sensorDS, pattern);

        // 3.获取结果
        SingleOutputStreamOperator<String> resultDS = sensorPS.select(new PatternSelectFunction<WaterSensor, String>() {
            /**
             * 处理匹配上的结果
             * @param pattern   Map，key是 模式名，value是一个List，存 匹配上的数据
             * @return
             * @throws Exception
             */
            @Override
            public String select(Map<String, List<WaterSensor>> pattern) throws Exception {
                return "获取结果: " + pattern;
            }
        });

        resultDS.print();


        env.execute();
    }
}
